/*
 * @Author: hx 2542123711@QQ.com
 * @Date: 2024-11-20 10:45:56
 * @LastEditors: hx 2542123711@QQ.com
 * @LastEditTime: 2024-11-20 22:24:08
 * @FilePath: /class_process-communication/NamePipe/server.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include<iostream>
#include"comm.hpp"
#include"log.hpp"

using namespace std;

int main()
{
    // cout << sum(4, 1, 2, 3, 4) << endl;
    Init init;//完成管道的创建和删除
    Log log;
    log.Enable(Onefile);

    //1.打开文件
    int fd = open(FIFO_FILE, O_RDONLY); //server在打开管道文件得时候会等待client端写入，进程阻塞  
    if(fd < 0)
    {
        // perror("open");
        log.logmessage(Debug, "mkfifo failed, error code:%d, error string:%s\n", errno, strerror(errno));
        exit(FILE_OPEN_ERROR);
    }

    cout << "server open file done" << endl;
    log.logmessage(Info, "mkfifo failed, error code:%d, error string:%s\n", errno, strerror(errno));
    log.logmessage(Debug, "mkfifo failed, error code:%d, error string:%s\n", errno, strerror(errno));
    log.logmessage(Warning, "mkfifo failed, error code:%d, error string:%s\n", errno, strerror(errno));
    log.logmessage(Error, "mkfifo failed, error code:%d, error string:%s\n", errno, strerror(errno));
    log.logmessage(Fatal, "mkfifo failed, error code:%d, error string:%s\n", errno, strerror(errno));

    //2.开始通信
    //server从管道文件中读
    while(true)
    {
        char buffer[MAX];
        buffer[0] = 0;
        int m = read(fd, buffer, sizeof(buffer));
        if(m > 0)
        {
            buffer[m] = 0;
            cout << buffer << endl;
        }
        else if(m == 0)
        {
            log.logmessage(Debug, "client quit me too, error code:%d, error string:%s", errno, strerror(errno));  
            break;
        }
        else break;
    }

    //3.关闭文件
    close(fd);
    
    return 0;
}